<template>
    <a-modal
        v-model:visible="showModal"
        :title="title"
        :width="520"
        :destroyOnClose="true"
        :maskClosable="false"
        :confirmLoading="loading"
        @ok="onSubmit"
        @cancel="handleCancle"
    >
        <a-form class="role-model" layout="horizontal" :model="formState" :rules="rules" ref="formRef">
            <a-form-item class="full-width" :label="t('yl.roleName')" name="name">
                <a-input v-model:value="formState.name" :placeholder="t('yl.inputNameStand')" />
            </a-form-item>
            <a-form-item :label="t('yl.roleLevel')">
                <a-input-number v-model:value="formState.level" :min="1" :max="9999" />
            </a-form-item>
            <a-form-item :label="t('yl.dataRange')">
                <a-select v-model:value="formState.dataScope" :placeholder="t('yl.pleaseSelectPost')">
                    <a-select-option v-for="item in dataRangeList" :key="item.id">
                        {{ item.name }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item :label="t('yl.dataPermission')" v-show="showDeptsTree" class="full-width" name="dept">
                <yl-treeselect-vue v-model:value="formState.depts"></yl-treeselect-vue>
            </a-form-item>
            <a-form-item :label="t('yl.description')" class="full-width">
                <a-textarea
                    v-model:value="formState.description"
                    placeholder="-"
                    :autoSize="{ minRows: 3, maxRows: 6 }"
                    allow-clear
                />
            </a-form-item>
        </a-form>
    </a-modal>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import _ from 'lodash';
import useDepts from '@/hooks/useDepts';
import ylTreeselectVue from '@/components/ylTreeselect.vue';

// 表单校验规则
const initRules = (t: fn) => {
    return {
        name: [{ required: true, message: t('yl.inputNameStand'), trigger: 'blur' }],
    };
};

export default defineComponent({
    name: 'roleModel',
    components: {
        ylTreeselectVue,
    },
    props: {
        visible: {
            type: Boolean,
            default: () => false,
        },
        title: {
            type: String,
        },
        loading: {
            type: Boolean,
            default: () => false,
        },
        role: {
            type: Object,
        },
    },
    emits: ['submit', 'cancle'],
    setup(props, { emit }) {
        const { t } = useI18n();
        const showModal = computed(() => props.visible);
        const formState = reactive({
            name: '', // 角色名
            dataScope: t('yl.all'), // 数据范围
            level: '1', // 级别
            depts: [], // 部门
            description: '', // 描述
            menus: [], // 菜单
            id: null,
        });

        // 编辑时赋值
        watch(
            () => props.role,
            (role) => {
                // if (_.isEmpty(role)) return;
                const { name, dataScope, depts, level, menus, description, id } = role as NormalObj;
                formState.name = name;

                formState.dataScope = dataScope;
                formState.depts = depts && depts.length ? depts.map((item: { id: number }) => item.id) : [];
                formState.level = level;
                formState.description = description;
                formState.id = id ? id : null;
                formState.menus = menus;
            }
        );
        // 数据范围选项
        const dataRangeList = [
            {
                id: t('yl.all'),
                name: t('yl.all'),
            },
            {
                id: t('yl.theSameLevel'),
                name: t('yl.theSameLevel'),
            },
            {
                id: t('yl.custom'),
                name: t('yl.custom'),
            },
        ];
        // 是否显示数据范围 - 自定义时显示
        const showDeptsTree = computed(() => formState.dataScope == t('yl.custom'));

        // 部门集合
        const deptState: NormalizeTableData = reactive({
            list: [],
            total: 0,
        });

        const queryDepts = async () => {
            const { list, total } = await useDepts();
            deptState.list = [...deptState.list, ...list];
            deptState.total = total;
        };

        onMounted(async () => {
            const timer = window.setTimeout(() => {
                queryDepts().then(() => {
                    clearTimeout(timer);
                }); // 预留
            }, 1000);
        });

        // 表单校验
        const rules = initRules(t);
        const formRef = ref();
        // 提交
        const onSubmit = () => {
            formRef.value.validate().then(() => {
                let { depts } = formState;
                // 多余的操作 接口数据类型问题
                const result = {
                    ...formState,
                    depts: !depts.length
                        ? []
                        : depts.map((item) => {
                              return {
                                  id: item,
                              };
                          }),
                };
                emit('submit', result);
            });
        };

        // 取消
        const handleCancle = () => {
            return emit('cancle');
        };

        return {
            formRef,
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
            showModal,
            formState,
            t,
            deptState,
            rules,
            onSubmit,
            handleCancle,
            dataRangeList,
            showDeptsTree,
        };
    },
});
</script>
<style lang="scss" scoped>
.role-model {
    @include flexWrap;
    width: 100%;
    .ant-form-item {
        @include flex;
        width: 50%;
        margin-right: 0;
        padding-right: $width10;
        margin-bottom: $width8;
        :deep .ant-form-item-label {
            flex-basis: $formLabel;
        }
        :deep .ant-form-item-control-wrapper {
            flex: 1;
        }
        :deep .ant-form-item-children,
        :deep .ant-input-number {
            width: 100%;
        }
        &.full-width {
            width: 100%;
        }
    }
}
</style>
